﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using deviceManage.Models;
using deviceManage.vo;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using deviceManage.Filters;
using deviceManage.Tools;
using deviceManage.VO;

namespace deviceManage.Controllers
{
    /// <summary>
    /// 巡检记录控制器
    /// </summary>
    [CheckLoginAttribute]
    public class CheckLogController : Controller
    {
        private readonly DeviceCtx _context;

        public CheckLogController(DeviceCtx context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            //是否只读权限
            int? flag = HttpContext.Session.GetInt32("viewFlag");
            return View(Tuple.Create(flag));
        }


        //ajax 获取分页数据,
        public AjaxResult List(int page, int limit)
        {
            AjaxResult r = new AjaxResult();
            IQueryable<DailyCheck> query = _context.DailyCheck;
          
            if (!string.IsNullOrWhiteSpace(Request.Form["startTime"]))
            {
                DateTime start = DateTime.Parse(Request.Form["startTime"]);
                query = query.Where(p => p.CheckDate >= start);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["endTime"]))
            {
                DateTime end = DateTime.Parse(Request.Form["endTime"]);
                query = query.Where(p => p.CheckDate <= end);
            }

            r.Count = query.Count();
            r.Code = 0;
            try
            {
                r.Data = query.OrderByDescending(p => p.CheckDate)
                .Skip((page - 1) * limit).Take(limit)
                .ToList();
            }
            catch (Exception e)
            {
                r.Msg = e.Message;
            }
            return r;
        }

        /// <summary>
        /// 显示设备入库页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string id)
        { 
            //获取model
            DailyCheck device = new DailyCheck();
            if (!string.IsNullOrWhiteSpace(id))
            {
                device = _context.DailyCheck.Single(p => p.Id == id);
                device.IsEdit = true;
            }
            else //自动生成ID
            {
                device.Id = System.Guid.NewGuid().ToString();
                device.IsEdit = false;
            }
            return View(Tuple.Create(device));
        }



        /// <summary>
        /// 显示设备入库页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Detail(string id)
        {
            //获取model
            DailyCheck device = new DailyCheck();
            if (!string.IsNullOrWhiteSpace(id))
            {
                device = _context.DailyCheck.Single(p => p.Id == id);
                device.IsEdit = true;
            }
             
            return View(Tuple.Create(device));
        }


        /// <summary>
        /// 删除巡检记录
        /// <returns></returns>
        public AjaxResult DeleteItem(string id)
        {
            //首先删除设备和机房
            var list = _context.DailyCheckRoom.Where(p => p.CheckId == id).ToList();
            foreach(var obj in list)
            {
                _context.DailyCheckRoom.Remove(obj);
            }
            _context.SaveChanges();

            var deviceList = _context.DailyCheckDevice.Where(p => p.CheckId == id).ToList();
            foreach (var obj in deviceList)
            {
                _context.DailyCheckDevice.Remove(obj);
                var device = _context.Device.Single(p => p.Id == obj.DeviceId);
                if (DeviceState.STATE_BAD.Equals(device.Status)) device.Status = DeviceState.STATE_NORMAL;
                _context.Device.Update(device);
            }
            _context.SaveChanges();

            //最后删除记录
            DailyCheck c = _context.DailyCheck.Single(p => p.Id == id);
            _context.DailyCheck.Remove(c);

            //更新
            _context.SaveChanges();

            return AjaxResult.GetOK("删除成功！");
        }


        /// <summary>
        /// 保存设备运维计划信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public AjaxResult Save(DailyCheck obj)
        {
            var exist = _context.DailyCheck.Any(p => p.Id == obj.Id);
            if (obj.Id == null || !exist)
            { //新增          
                obj.CreateDate = DateTime.Now;
                obj.CreateUserId = HttpContext.Session.GetString(WebContext.SESSION_KEY_USER_ID);
                _context.DailyCheck.Add(obj);
                _context.SaveChanges();                
            }
            else
            {
                DailyCheck device = _context.DailyCheck.Single(p => p.Id == obj.Id);
                device.Remark = obj.Remark;
                device.CheckDate = obj.CheckDate;
                device.CheckUser = obj.CheckUser;
                this._context.SaveChanges(); //保存                
            } 

            return AjaxResult.GetOK("保存成功");
        }

        /// <summary>
        ///  选择机房
        /// </summary>
        /// <param name="id">设备ID</param>
        /// <returns></returns>
        public IActionResult SelectRoom(string id)
        {
            //下拉列表
            var list = _context.Room.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList();
            return View(Tuple.Create(id,list));
        }
        /// <summary>
        /// 保存机房
        /// <returns></returns>
        public AjaxResult doAddRoom(DailyCheckRoom room)
        {
            var exist = _context.DailyCheckRoom.Any(p => p.RoomId == room.RoomId && p.CheckId == room.CheckId);
            if (exist)
            {
                return AjaxResult.GetError("机房已经存在！");
            }

            _context.DailyCheckRoom.Add(room);
            _context.SaveChanges();

            return AjaxResult.GetOK("添加成功！"); 
        }

        /// <summary>
        /// 删除机房
        /// <returns></returns>
        public AjaxResult DeleteRoom(string id)
        {
            DailyCheckRoom room = _context.DailyCheckRoom.Single(p => p.Id == id);
            _context.DailyCheckRoom.Remove(room);
            _context.SaveChanges();

            return AjaxResult.GetOK("删除成功！");
        }
        

        /// <summary>
        /// 获取巡检记录中的机房列表
        /// </summary> 
        public AjaxResult CheckRoomList(string id)
        {
            AjaxResult r = new AjaxResult();
            IQueryable<DailyCheckRoom> query = _context.DailyCheckRoom.Where(p => p.CheckId == id);
            r.Count = query.Count();
            r.Code = 0;
            try
            {
                r.Data = query.Include(p => p.Room).ToList();
            }
            catch (Exception e)
            {
                r.Msg = e.Message;
            }
            return r;
        }



        /// <summary>
        ///  选择设备
        /// </summary>
        /// <param name="id">设备ID</param>
        /// <returns></returns>
        public IActionResult SelectDevice(string id)
        {
            //下拉列表
            var typeList = _context.DeviceType.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList();
            return View(Tuple.Create(id, typeList));
        }


        /// <summary>
        /// 获取设备列表，用于添加设备到计划中
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="name">设备名称</param>
        /// <param name="id">计划ID</param>
        /// <returns></returns>
        public AjaxResult SelectDeviceList(int page, int limit, String name, string id, String deviceTypeId, String deviceId)
        {
            AjaxResult r = new AjaxResult();
            var q = _context.Device.FromSql($"select t1.*  from device t1 left join daily_check_device t2 on t1.id = t2.device_id and t2.check_id = {id}  where t2.id is null");

            if (!string.IsNullOrWhiteSpace(name))
            {
                q = q.Where(p => p.Name.Contains(name));
            }

            if (!string.IsNullOrWhiteSpace(deviceTypeId))
            {
                q = q.Where(p => p.DeviceTypeId == deviceTypeId);
            }

            if (!string.IsNullOrWhiteSpace(deviceId))
            {
                q = q.Where(p => p.DeviceId == deviceId);
            }

            r.Data = q.Include(p => p.DeviceType).Include(p => p.Room).ToList();
            return r;
        }

        /// <summary>
        ///损坏设备列表
        /// </summary>      
        /// <param name="id">计划ID</param>
        /// <returns></returns>
        public AjaxResult BadDeviceList(string id)
        {
            AjaxResult r = new AjaxResult();
            IQueryable<DailyCheckDevice> query = _context.DailyCheckDevice.Where(p=>p.CheckId == id);             
            r.Count = query.Count();
            r.Code = 0;
            try
            {
                r.Data = query.Include(p => p.Device).ThenInclude(p=>p.DeviceType).ToList();
            }
            catch (Exception e)
            {
                r.Msg = e.Message;
            }
            return r;
        }

        /// <summary>
        /// 添加设备到计划中
        /// </summary>
        /// <param name="deviceId">设备ID</param>
        /// <param name="planId">计划ID</param>
        /// <returns></returns>
        public AjaxResult AddDeviceToLog(string deviceId,string checkId,string remark)
        {
            DailyCheckDevice item = new DailyCheckDevice();
            item.DeviceId = deviceId;
            item.Remark = remark;
            item.CheckId = checkId;
            _context.DailyCheckDevice.Add(item);


            //标记设备为损坏
            Device device = _context.Device.Single(p => p.Id == item.DeviceId);
            device.Status = DeviceState.STATE_BAD;
            _context.Device.Update(device);

            //更新
            _context.SaveChanges();

            return AjaxResult.GetOK("添加成功！");

        }

        
        /// <summary>
        /// 删除设备
        /// <returns></returns>
        public AjaxResult DeleteDevice(string id)
        {
            DailyCheckDevice room = _context.DailyCheckDevice.Single(p => p.Id == id);
            _context.DailyCheckDevice.Remove(room);


            //更新状态为正常
            Device device = _context.Device.Single(p => p.Id == room.DeviceId);
            if (DeviceState.STATE_BAD.Equals(device.Status))
            {
                device.Status = DeviceState.STATE_NORMAL;
            }
            _context.Device.Update(device);

            //保存更新
            _context.SaveChanges();

            return AjaxResult.GetOK("删除成功！");
        }
    }
}